from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from web.settings import BASE_DIR
from .. import models
from django.contrib.auth.hashers import make_password, check_password

# Create your views here.

# 后台首页
def index(request):
    return render(request,'myadmin/index.html')
# 会员添加
def user_add(request):
    return render(request,'myadmin/user/add.html')
# 执行会员添加
def user_insert(request):
    ob = models.User()
    res_dict = request.POST.dict()
    upass = make_password(res_dict['pwd'], None, 'pbkdf2_sha256')
    print(upass)
    res_dict.pop('csrfmiddlewaretoken')
    img_address = get_img(request)
    ob.username = res_dict['username']
    ob.password = upass
    ob.nkiname = res_dict['nkiname']
    ob.sex = res_dict['sex']
    ob.age = res_dict['age']
    ob.phone = res_dict['phone']
    ob.email = res_dict['email']
    ob.address = res_dict['address']
    ob.pic = img_address
    ob.save()
    return HttpResponse('<script>alert("添加成功");location.href="/myadmin/user/list/"</script>')
# 会员列表
def user_list(request):
    # if request.method =='GET':
    res = request.GET.dict()
    if 'types' in res.keys():
        if res['types'] == 'all':
            from django.db.models import Q
            userlist = models.User.objects.filter(Q(nkiname__contains=res['keywords'])|Q(phone__contains=res['keywords'])|Q(email__contains=res['keywords']))
    else:
        userlist = models.User.objects.all()
    # if request.method == 'POST':
    from django.core.paginator import Paginator
    # 实例化分页类
    paginator = Paginator(userlist,10)
    page_count = paginator.num_pages
    p = int(request.GET.get('p',1))
    # 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
    userslist= paginator.page(p)
    context = {'userlist':userslist}
    return render(request,'myadmin/user/list.html',context)
    return HttpResponse('ok')
def user_edit(request):
    if request.method == 'GET':
        uid = request.GET.get('id')
        data = models.User.objects.get(id=uid)
        return render(request,'myadmin/user/edit.html',{'data':data})
    elif request.method == 'POST':
        uid = request.GET.get('id')
        data = models.User.objects.get(id=uid)
        res_dict = request.POST.dict()
        myfile = request.FILES.get("pic",None)
        if myfile:
            import time
            import os
            print(BASE_DIR+str(data.pic))
            os.remove(BASE_DIR+str(data.pic))
            filename = str(time.time())+"."+myfile.name.split('.').pop()
            img_address = "/static/img/"+filename
            destination = open(BASE_DIR+img_address,"wb+")
            for chunk in myfile.chunks():      # 分块写入文件  
                destination.write(chunk)  
            destination.close()
            data.pic = img_address
        data.nkiname = res_dict['nkiname']
        data.sex = res_dict['sex']
        data.age = res_dict['age']
        data.phone = res_dict['phone']
        data.email = res_dict['email']
        data.address = res_dict['address']
        data.save()
        return HttpResponse('<script>alert("编辑成功");location.href="/myadmin/user/list/"</script>')

def edit_static(request):
    res = request.GET.dict()
    print(int(res['sta']))
    data = models.User.objects.get(id=res['id'])
    data.statics = int(res['sta'])
    data.save()
    return JsonResponse({'msg':'ok'})


def get_img(request):
    myfile = request.FILES.get("pic",None)
    if not myfile:
        return HttpResponse('<script>alert("请上传头像");location.href="javascript:history.back()"</script>')
    else:
        import time
        filename = str(time.time())+"."+myfile.name.split('.').pop()
        img_address = "/static/img/"+filename
        destination = open(BASE_DIR+img_address,"wb+")
        for chunk in myfile.chunks():      # 分块写入文件  
            destination.write(chunk)  
        destination.close()
    return img_address

